package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
@Component
public class CacheClient {

    private static final ExecutorService CACHE_REBUILT_EXECUTOR = Executors.newFixedThreadPool(10);
    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 存入redis
     *
     * @param key
     * @param value
     * @param time
     * @param unit
     */
    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    /**
     * 存入逻辑过期
     *
     * @param key
     * @param value
     * @param time
     * @param unit
     */
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 解决缓存穿透工具类
     *
     * @param id
     * @return
     */
    private <R, ID> R queryWithPassThrough
                (String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallBack, Long time, TimeUnit timeUnit) {
        //  从Redis中获取
        String json = stringRedisTemplate.opsForValue().get(keyPrefix + id);
        //  判断是否为空
        if (json != null && !json.isEmpty()) {
            //  不为空 返回
            return BeanUtil.toBean(json, type);
        }

        //  为空从Redis中获取
        R r = dbFallBack.apply(id);

        //  判断是否获取成功
        if (r == null) {
            //  获取失败 存入空值
            stringRedisTemplate.opsForValue().set(keyPrefix + id, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //  获取成功 存入Redis并返回
        set(keyPrefix + id, r, time, timeUnit);
        return r;
    }

    /**
     * 逻辑过期解决缓存击穿工具类
     *
     * @param id
     * @return
     */
    private <R, ID> R queryWithLogicalExpire
                    (String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallBack, Long time, TimeUnit timeUnit) {
        //  从Redis中获取数据
        String json = stringRedisTemplate.opsForValue().get(keyPrefix + id);

        //  判断数据是否存在
        if (json == null || json.isEmpty()) {
            //  不存在 返回空
            return null;
        }

        //  存在 反序列化json
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();

        //  判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            return r;
        }

        if (tryLock(keyPrefix + id)) {
            try {
                CACHE_REBUILT_EXECUTOR.submit(() -> {
                    R r1 = dbFallBack.apply(id);
                    setWithLogicalExpire(keyPrefix+id, r1, time, timeUnit);
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                unlock(keyPrefix + id);
            }
        }

        return r;

    }


    /**
     * 获取互斥锁
     *
     * @param key
     * @return
     */
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放互斥锁
     *
     * @param key
     */
    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }
}
